<template>
	<view class="">
		<tn-nav-bar :isBack="false" bgClass="bg-gradual-blue">创耐锂电</tn-nav-bar>
		<view :style="{paddingTop: vuex_custom_bar_height + 'px'}">

			<view style="height: 8vh;">
				<view class="text-bold padding text-xxl lines-grey flex align-end justify-end" style="line-height: 2;">
					<text @click.stop="showGuide = true">
						使用说明
					</text>
					<text @click.stop="showGuide = true" class="padding-left-xs tn-icon-help"></text>
				</view>
			</view>

			<view class="margin-sm" style="flex-direction: column;">
				<tn-button :fontSize='32' fontBold :shadow="true" width="100%" height="100rpx"
					backgroundColor="tn-main-gradient-indigo" margin="10px 0" @click="toBleList(1)">版本 V1.0</tn-button>
				<tn-button :fontSize='32' fontBold :shadow="true" width="100%" height="100rpx"
					backgroundColor="tn-cool-bg-color-7" margin="10px 0" @click="toBleList(2)">版本 V2.0</tn-button>
				<tn-button :fontSize='32' fontBold :shadow="true" width="100%" height="100rpx"
					backgroundColor="tn-cool-bg-color-6" margin="10px 0" @click="toBleList(3)">版本 V3.0</tn-button>
				<tn-button :fontSize='32' fontBold :shadow="true" width="100%" height="100rpx"
					backgroundColor="tn-cool-bg-color-5" margin="10px 0" @click="toBleList(11)">版本 MT-V3.0</tn-button>
			</view>
		</view>
		<view class="margin-sm" style="position: absolute;bottom: 5px;">
			<tn-button :fontSize='32' fontBold :shadow="true" width="375px" height="100rpx"
				backgroundColor="tn-cool-bg-color-14" margin="10px 0" @click="toDemo()">演示页面</tn-button>
		</view>


		<!-- 使用说明弹窗 -->
		<UsageGuideModal :show="showGuide" @update:show="showGuide = $event" @closed='onGuideClosed' />

		<!-- 模态框 -->
		<tn-modal v-model="modelShow" width="84%" :radius="12" custom :button="[
		  {
		    text: '确定',
		    backgroundColor: 'tn-bg-indigo',
		    fontColor: '#FFFFFF'
		  },{
		    text: '取消',
		    backgroundColor: 'tn-bg-grey',
		    fontColor: '#FFFFFF'
		  }
		]" showCloseBtn :maskCloseable="false" zoom @click="btnFun" @cancel='toClose'>
			<view class="custom-modal-content">
				<view class="text-bold text-xl">是否自动连接上次使用的设备？</view>
				<view class="text-lg tn-margin">
					<text>{{context}}</text>
				</view>
			</view>
		</tn-modal>


	</view>
</template>

<script>
	import bleData from "@/libs/protocol/tianyi/bleData.js";
	import CRC from "@/libs/protocol/tianyi/CRC16.js";
	import BLE from "@/libs/bluetooth/BLE.js";
	import store from '@/store/index.js'

	import UsageGuideModal from './UsageGuideModal.vue'

	export default {
		components: {
			UsageGuideModal
		},
		data() {
			return {
				showGuide: false,
				modelShow: false,
				versions: ['版本 V1.0', '版本 V2.0', '版本 V3.0', '版本MT-V3.0'],
				context: null,
			}
		},
		onLoad() {
			// #ifdef MP-WEIXIN
			//初始化蓝牙 检查蓝牙是否开启
			BLE.Init()
			// #endif
			setTimeout(() => {
				//判断之前是否重新连接
				let id = store.state.vuex_ble_id
				let version = store.state.vuex_ble_version
				let name = store.state.vuex_ble_name
				if (id && version) {
					let context = null;
					if (version * 1 < 10) {
						context = this.versions[version * 1 - 1]
					} else {
						context = this.versions[3]
					}
					context = context + '【' + name + '】'
					this.context = context
					this.modelShow = true
				}
			}, 1000)

			//验证CRC16
			function checkCRC16(hexString) {
				// 移除可能存在的空格或非十六进制字符
				const cleanHex = hexString.replace(/[^0-9A-Fa-f]/g, '');
				// 确保是偶数个字符，每两个字符代表一个字节
				if (cleanHex.length % 2 !== 0) {
					throw new Error("十六进制字符串长度必须为偶数");
				}
				let sum = 0;
				// 遍历每两个字符（一个字节）
				for (let i = 0; i < cleanHex.length; i += 2) {
					const byteHex = cleanHex.substr(i, 2);
					const byteValue = parseInt(byteHex, 16);
					sum += byteValue;
				}
				// 取反，得到校验码
				let checksum = (~sum + 1) & 0xFFFF; // 同样保留低16位
				// 转换为4位大写十六进制字符串
				return checksum.toString(16).toUpperCase().padStart(4, '0');
			}
			// console.log(('12'*1).toString(16).toUpperCase().padStart(4, '0'));

			//console.log(checkCRC16('FA070016020708076C'));

			const isFirstIn = uni.getStorageSync('isFirstIn')
			if (isFirstIn) {

			} else {
				this.showGuide = true
			}
		},
		onShow() {
			if (getApp().globalData.bleObj.state) {
				BLE.Close()
			}
		},
		methods: {
			toDemo() {
				uni.navigateTo({
					url: '/pages_ble/demo/demo'
				})
			},
			toView() {
				uni.navigateTo({
					url: '/pages/webview/index'
				})
			},
			onGuideClosed() {
				const isFirstIn = uni.getStorageSync('isFirstIn')
				if (!isFirstIn) {
					uni.setStorageSync('isFirstIn', {
						count: 1
					})
				} else {
					isFirstIn.count++
					uni.setStorageSync('isFirstIn', isFirstIn)
				}

			},
			btnFun(event) {
				if (event.index > 0) {
					this.toClose()
				} else {
					let version = store.state.vuex_ble_version * 1
					if (version === 11) {
						uni.reLaunch({
							url: '/pages_ble/mingtang/index?id=' + store.state.vuex_ble_id
						})
					} else {
						getApp().globalData.bleVersion = version
						let item = {
							deviceId: store.state.vuex_ble_id,
							mac: store.state.vuex_ble_id,
							name: store.state.vuex_ble_name,
						}
						BLE.Connect(item.deviceId, function() {
							let bleVersion = getApp().globalData.bleVersion
							if (!bleVersion || bleVersion * 1 < 0) {
								uni.showToast({
									icon: 'none',
									title: '未选择版本信息'
								})
							} else {
								getApp().globalData.bleObj.MAC = item.mac
								getApp().globalData.bleObj.name = item.name

								uni.showToast({
									icon: 'none',
									title: '连接成功'
								})
								setTimeout(() => {
									if (bleVersion * 1 === 1) {
										uni.reLaunch({
											url: '/pages_ble/ble/tianyi?name=' + item.name
										})
									} else if (bleVersion * 1 === 2) {
										uni.reLaunch({
											url: '/pages_ble/ble/superpower?name=' + item.name
										})
									} else if (bleVersion * 1 === 3) {
										uni.reLaunch({
											url: '/pages_ble/ble/jiabaida?name=' + item.name
										})
									}
								}, 500)
							}
						});
					}
				}
			},
			toClose() {
				this.modelShow = false
				store.commit('$tStore', {
					name: 'vuex_ble_version',
					value: ''
				})
				store.commit('$tStore', {
					name: 'vuex_ble_id',
					value: ''
				})
				store.commit('$tStore', {
					name: 'vuex_ble_name',
					value: ''
				})
			},
			toDemo() {
				uni.navigateTo({
					url: '/pages_ble/ble/view'
				})
			},
			toBleList(v) {
				//定义 v>10 为 不连接蓝牙版本
				if (v && v > 10) {
					if (v === 11) {
						store.commit('$tStore', {
							name: 'vuex_ble_version',
							value: 11
						})
						uni.navigateTo({
							url: '/pages_ble/mingtang/index?v=' + v
						})
					}
					return
				}
				getApp().globalData.bleVersion = v * 1
				store.commit('$tStore', {
					name: 'vuex_ble_version',
					value: v * 1
				})
				uni.navigateTo({
					url: '/pages_ble/blelist/blelist?v=' + v
				})
			}
		}
	}
</script>